package com.daoyintech.services;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

/**
 * Created by xuzhaolin on 15/12/28.
 */
@Service

public class WeixinPayService implements EnvironmentAware{

    @Autowired
    private ResourceLoader resourceLoader;

    private static final String fileName = "apiclient_cert";
    private static final String extName = ".p12";
    private Resource resource;

    private RelaxedPropertyResolver propertyResolver;



    @Override
    public void setEnvironment(Environment environment) {
        this.propertyResolver = new RelaxedPropertyResolver(environment,"weixin.");
    }

    @PostConstruct
    public void initialize() throws Exception {
        resource = resourceLoader.getResource("classpath:"+fileName+extName);
    }

    public ClientHttpRequestFactory wxPayHttpClient() throws Exception{
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        File file = resource.getFile();
        FileInputStream inputStream = new FileInputStream(file);
        try {
           keyStore.load(inputStream,propertyResolver.getProperty("store_id").toCharArray());
        }finally {
            inputStream.close();
        }

        final SSLContext sslContext = SSLContexts.custom().
                                 loadKeyMaterial(keyStore,propertyResolver.getProperty("store_id").toCharArray()).build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        return new HttpComponentsClientHttpRequestFactory(httpclient);
    }
}
